package com.lw.lost.daos

import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase

class MessageDao(private val db: SQLiteDatabase) {
    
    fun insert(senderId: Long, receiverId: Long, content: String, imageUrl: String? = null): Long {
        val values = ContentValues().apply {
            put("senderId", senderId)
            put("receiverId", receiverId)
            put("content", content)
            put("imageUrl", imageUrl)
            put("isRead", 0)
        }
        return db.insert("messages", null, values)
    }

    fun getMessageHistory(userId1: Long, userId2: Long): Cursor {
        return db.rawQuery("""
            SELECT m.*, u.avatar
            FROM messages m
            LEFT JOIN users u ON m.senderId = u.userId
            WHERE (m.senderId = ? AND m.receiverId = ?)
            OR (m.senderId = ? AND m.receiverId = ?)
            ORDER BY m.sendTime ASC
        """, arrayOf(userId1.toString(), userId2.toString(), userId2.toString(), userId1.toString()))
    }

    fun markAsRead(senderId: Long, receiverId: Long) {
        val values = ContentValues().apply {
            put("isRead", 1)
        }
        db.update(
            "messages",
            values,
            "senderId = ? AND receiverId = ? AND isRead = 0",
            arrayOf(senderId.toString(), receiverId.toString())
        )
    }

    fun deleteConversation(userId1: Long, userId2: Long): Int {
        return db.delete(
            "messages",
            "(senderId = ? AND receiverId = ?) OR (senderId = ? AND receiverId = ?)",
            arrayOf(userId1.toString(), userId2.toString(), userId2.toString(), userId1.toString())
        )
    }

    // 获取某个用户的所有未读消息数
    fun getUnreadCount(userId: Long): Int {
        return db.rawQuery("""
            SELECT COUNT(*) FROM messages 
            WHERE receiverId = ? AND isRead = 0
        """, arrayOf(userId.toString())).use { cursor ->
            if (cursor.moveToFirst()) {
                cursor.getInt(0)
            } else {
                0
            }
        }
    }

    // 获取来自特定发送者的未读消息数
    fun getUnreadCountFromSender(receiverId: Long, senderId: Long): Int {
        return db.rawQuery("""
            SELECT COUNT(*) FROM messages 
            WHERE receiverId = ? AND senderId = ? AND isRead = 0
        """, arrayOf(receiverId.toString(), senderId.toString())).use { cursor ->
            if (cursor.moveToFirst()) {
                cursor.getInt(0)
            } else {
                0
            }
        }
    }
} 